// Project name:JavaRedis
// Creator:muhong
// Date time:2023/7/24,10:54 上午
// Name:SystemPropertiesUtil

package org.gmh.util.internal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.AccessController;
import java.security.PrivilegedAction;

public class SystemPropertyUtil {
    private final static Logger logger = LoggerFactory.getLogger(SystemPropertyUtil.class);


    public static boolean contain(String key) {
        return false;
    }

    public static String get(String key) {
        return get(key, null);
    }

    public static  boolean getBoolean(String key, boolean def){
        String value = get(key);
        if (value == null){
            return  def;
        }
        value = value.trim().toLowerCase();
        if (value.isEmpty()){
            return def;
        }
        if ("true".equals(value) || "yes".equals(value) || "1".equals(value)){
            return true;
        }
        if ("false".equals(value) || "no".equals(value) || "0".equals(value)){
            return false;
        }
        return def;
    }

    public static long getLong(String key, long def) {

        String value = get(key);
        if (value == null) {
            return def;
        }
        value = value.trim();
        try {
            return Long.parseLong(value);
        } catch (Exception e) {

        }
        logger.warn("Unable to parse system property {}, {}, use default value {}", key, value, def);
        return def;
    }

    public static String get(final String key, String def) {
        if (key == null) {
            throw new NullPointerException("key");
        }
        if (key.isEmpty()) {
            throw new IllegalArgumentException("key must not be empty");
        }
        String value = null;
        try {
            if (System.getSecurityManager() == null) {
                value = System.getProperty(key);
            } else {
                value = AccessController.doPrivileged(new PrivilegedAction<String>() {
                    @Override
                    public String run() {
                        return System.getProperty(key);
                    }
                });
            }
        } catch (SecurityException e) {
            logger.warn("Unable to retrieve a system property {}, default values will be used", key, e);
        }
        if (value == null) {
            return def;
        }

        return value;
    }
}
